package com.polarrose.amazon.sqs.impl;

import java.util.List;
import java.util.Map;

import com.polarrose.amazon.sqs.QueueAttribute;
import com.polarrose.amazon.sqs.SqsExtendedService;
import com.polarrose.amazon.sqs.SqsQueue;

public class SqsExtendedServiceImpl extends SqsCoreServiceImpl implements SqsExtendedService {

	public SqsQueue lookupQueueByName(String name) {
		return lookupQueueByName(name, false);
	}

	public SqsQueue lookupQueueByName(String name, boolean createIfNotExists) {
		List<SqsQueue> listQueues = listQueues(name);
		SqsQueue queue = null;
		for (SqsQueue sqsQueue : listQueues) {
			if (sqsQueue.getName().equals(name)) {
				queue = sqsQueue;
				break;
			}
		}

		if (queue == null && createIfNotExists) {
			queue = createQueue(name);
		}
		return queue;
	}

	public void purgeQueue(String name) {
		SqsQueue queue = new SqsQueue(name);
		Map<QueueAttribute, Object> queueAttributes = getQueueAttributes(queue, QueueAttribute.VisibilityTimeout);

		Integer visibilityTimeout = (Integer) queueAttributes.get(QueueAttribute.VisibilityTimeout);
		deleteQueue(queue);
		try {
			Thread.sleep(65000);
		} catch (InterruptedException e) {
			return;
		}
		createQueue(name, visibilityTimeout);
	}
}
